package org.jsola.hr.service.impl;

import org.jsola.core.Page;
import org.jsola.hr.common.ExampleKit;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dao.IChannelCompanyDAO;
import org.jsola.hr.dto.ChannelCompanyAddDTO;
import org.jsola.hr.dto.ChannelCompanyUpdateDTO;
import org.jsola.hr.entity.ChannelCompanyDO;
import org.jsola.hr.provider.IPermissionProviderService;
import org.jsola.hr.provider.IUserProviderService;
import org.jsola.hr.query.ChannelCompanyQuery;
import org.jsola.hr.service.IChannelCompanyService;
import org.jsola.hr.service.IChildCompanyService;
import org.jsola.hr.service.ICompanyService;
import org.jsola.hr.vo.ChannelCompanyListVO;
import org.jsola.hr.vo.ChannelCompanyVO;
import org.jsola.hr.vo.ChildCompanyListVO;
import org.jsola.hr.vo.CompanyVO;
import org.jsola.user.core.TokenUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.*;
import java.util.stream.Collectors;

import static org.jsola.hr.constant.HrPermissionConstants.SUPER_COMPANY_ADMIN;

/**
 * 渠道用工单位
 *
 * @author zhr
 */
@Service("hrChannelCompanyServiceImpl")
public class ChannelCompanyServiceImpl implements IChannelCompanyService {

    @Autowired
    private IChannelCompanyDAO channelCompanyDAO;

    @Autowired
    private IUserProviderService userProviderService;

    @Autowired
    private ICompanyService companyService;

    @Autowired
    private IChildCompanyService childCompanyService;

    @Autowired
    private IPermissionProviderService permissionProviderService;

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public ChannelCompanyVO save(ChannelCompanyAddDTO channelCompanyAddDTO, TokenUser tokenUser) {
        // 转DO
        ChannelCompanyDO channelCompanyDO = channelCompanyAddDTO.to(ChannelCompanyDO.class);
        // 保存
        channelCompanyDO = save(channelCompanyDO, tokenUser.getSiteId(), tokenUser.getUserId());
        return channelCompanyDO.to(ChannelCompanyVO.class);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public List<ChannelCompanyVO> batchSave(List<ChannelCompanyAddDTO> channelCompanyAddDTOList, TokenUser tokenUser) {
        if (CollectionUtils.isEmpty(channelCompanyAddDTOList)) {
            return null;
        }
        List<ChannelCompanyDO> channelCompanyDOList = channelCompanyAddDTOList
                .parallelStream()
                .map(channelCompanyAddDTO -> {
                    ChannelCompanyDO channelCompanyDO = channelCompanyAddDTO.to(ChannelCompanyDO.class);
                    channelCompanyDO.preInsert(tokenUser.getUserId());
                    channelCompanyDO.setSiteId(tokenUser.getSiteId());
                    return channelCompanyDO;
                }).collect(Collectors.toList());
        channelCompanyDAO.insertListAndSetId(channelCompanyDOList);
        return channelCompanyDOList
                .parallelStream()
                .map(channelCompanyDO -> channelCompanyDO.to(ChannelCompanyVO.class))
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int update(ChannelCompanyUpdateDTO channelCompanyUpdateDTO, TokenUser tokenUser) {
        //转DO
        ChannelCompanyDO channelCompanyDO = channelCompanyUpdateDTO.to(ChannelCompanyDO.class);
        //根据主键更新，只更新非null值
        return updateByIdSelective(channelCompanyDO, tokenUser.getSiteId(), tokenUser.getUserId());
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int deleteByIds(TokenUser tokenUser, String... channelCompanyIds) {
        return logicalDeleteByIds(tokenUser.getSiteId(), tokenUser.getUserId(), (Object[]) channelCompanyIds);
    }


    @Override
    public ChannelCompanyVO selectById(String channelCompanyId, String siteId) {
        ChannelCompanyDO channelCompanyDO = selectDOById(channelCompanyId, siteId);
        if (channelCompanyDO == null) {
            return null;
        }
        return channelCompanyDO.to(ChannelCompanyVO.class);
    }

    @Override
    public List<ChannelCompanyListVO> select(ChannelCompanyQuery channelCompanyQuery, String siteId) {
        List<ChannelCompanyDO> channelCompanyDOList = selectDO(channelCompanyQuery, siteId);
        if (CollectionUtils.isEmpty(channelCompanyDOList)) {
            return channelCompanyDOList == null ? null : new ArrayList<>();
        }
        return channelCompanyDOList.stream()
                .map(channelCompanyDO -> channelCompanyDO.to(ChannelCompanyListVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public int selectCount(ChannelCompanyQuery channelCompanyQuery, String siteId) {
        Example example = buildExample(channelCompanyQuery, siteId);
        return channelCompanyDAO.selectCountByExample(example);
    }

    @Override
    public Page<ChannelCompanyListVO> selectPage(ChannelCompanyQuery channelCompanyQuery, String siteId) {
        Example example = buildExample(channelCompanyQuery, siteId);
        Page<ChannelCompanyDO> page = channelCompanyDAO.selectPageByExample(example,
                channelCompanyQuery.getPageNo(),
                channelCompanyQuery.getPageSize());

        return page.to(ChannelCompanyListVO.class);
    }

    @Override
    public ChannelCompanyDO selectDOById(String channelCompanyId, String siteId) {
        return listById(channelCompanyId, siteId);
    }

    @Override
    public List<ChannelCompanyDO> selectDO(ChannelCompanyQuery channelCompanyQuery, String siteId) {
        Example example = buildExample(channelCompanyQuery, siteId);
        return channelCompanyDAO.selectByExample(example);
    }

    @Override
    public void saveChannel(String channelId, Boolean isAllChildCompany, List<String> childCompanyIdList
            , List<String> employerIdList, TokenUser tokenUser) {
        // 全部用工单位
        if (isAllChildCompany != null && isAllChildCompany) {
            ChannelCompanyAddDTO channelCompanyAddDTO = new ChannelCompanyAddDTO();
            channelCompanyAddDTO.setChannelId(channelId);
            channelCompanyAddDTO.setChildCompanyId(SUPER_COMPANY_ADMIN);
            channelCompanyAddDTO.setIsAllEmployer(true);
            channelCompanyAddDTO.setEmployerId(null);
            channelCompanyAddDTO.setIsAllChildCompany(true);
            save(channelCompanyAddDTO, tokenUser);
            return;
        }
        List<ChannelCompanyAddDTO> channelCompanyAddDTOList = new ArrayList<>();
        // 保存用工单位分组
        if (!CollectionUtils.isEmpty(childCompanyIdList)) {
            // 去重
            childCompanyIdList = childCompanyIdList.parallelStream().distinct().collect(Collectors.toList());
            for (String childCompanyId : childCompanyIdList) {
                ChannelCompanyAddDTO channelCompanyAddDTO = new ChannelCompanyAddDTO();
                channelCompanyAddDTO.setChannelId(channelId);
                channelCompanyAddDTO.setChildCompanyId(childCompanyId);
                channelCompanyAddDTO.setIsAllEmployer(true);
                channelCompanyAddDTO.setEmployerId(null);
                channelCompanyAddDTO.setIsAllChildCompany(false);
                channelCompanyAddDTOList.add(channelCompanyAddDTO);
            }
        }
        // 保存用工单位
        if (!CollectionUtils.isEmpty(employerIdList)) {
            // 去重
            employerIdList = employerIdList.parallelStream().distinct().collect(Collectors.toList());
            for (String employerId : employerIdList) {
                ChannelCompanyAddDTO channelCompanyAddDTO = new ChannelCompanyAddDTO();
                channelCompanyAddDTO.setChannelId(channelId);
                channelCompanyAddDTO.setChildCompanyId(null);
                channelCompanyAddDTO.setIsAllEmployer(false);
                channelCompanyAddDTO.setEmployerId(employerId);
                channelCompanyAddDTO.setIsAllChildCompany(false);
                channelCompanyAddDTOList.add(channelCompanyAddDTO);
            }
        }
        if (!CollectionUtils.isEmpty(channelCompanyAddDTOList)) {
            // 批量保存
            batchSave(channelCompanyAddDTOList, tokenUser);
        }
    }

    @Override
    public void saveOrUpdateChannel(String channelId, Boolean isAllChildCompany, List<String> childCompanyIdList
            , List<String> employerIdList, TokenUser tokenUser) {
        // 分管用工单位
        List<ChannelCompanyVO> channelCompanyVOList = selectByChannelId(channelId, tokenUser.getSiteId());
        // 删除旧的
        if (!CollectionUtils.isEmpty(channelCompanyVOList)) {
            deleteByIds(tokenUser, channelCompanyVOList.parallelStream().map(ChannelCompanyVO::getId).toArray(String[]::new));
        }
        // 创建新的
        saveChannel(channelId, isAllChildCompany, childCompanyIdList, employerIdList, tokenUser);
    }

    @Override
    public List<ChannelCompanyVO> selectByChannelId(String channelId, String siteId) {
        Example example = new Example(ChannelCompanyDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId)
                .andEqualTo("channelId", channelId);
        List<ChannelCompanyDO> channelCompanyDOList = channelCompanyDAO.selectByExample(example);
        if (CollectionUtils.isEmpty(channelCompanyDOList)) {
            return new ArrayList<>();
        }
        return channelCompanyDOList.parallelStream().map(channelCompanyDO
                -> channelCompanyDO.to(ChannelCompanyVO.class)).parallel().collect(Collectors.toList());
    }

    @Override
    public List<ChannelCompanyVO> selectByChannelIds(List<String> channelIds, String siteId) {
        if (CollectionUtils.isEmpty(channelIds)) {
            return new ArrayList<>();
        }
        Example example = new Example(ChannelCompanyDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId)
                .andIn("channelId", channelIds);
        List<ChannelCompanyDO> channelCompanyDOList = channelCompanyDAO.selectByExample(example);
        if (CollectionUtils.isEmpty(channelCompanyDOList)) {
            return new ArrayList<>();
        }
        return channelCompanyDOList.parallelStream().map(channelCompanyDO
                -> channelCompanyDO.to(ChannelCompanyVO.class)).parallel().collect(Collectors.toList());
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public List<ChildCompanyListVO> selectChildCompanyByChannelCompanyList(List<ChannelCompanyVO> channelCompanyVOList, String siteId) {
        // 查询公司下完整的用工单位树形结构
        List<ChildCompanyListVO> childCompanyListVOList = childCompanyService.selectAllTreeCompany(siteId);
        // 是否有总公司权限
        if (channelCompanyVOList.parallelStream().anyMatch(ChannelCompanyVO::getIsAllChildCompany)) {
            // 有总公司权限 最外层放入总公司
            ChildCompanyListVO childCompanyListVO = new ChildCompanyListVO();
            String siteName = permissionProviderService.getSiteName(siteId);
            childCompanyListVO.setName(siteName);
            childCompanyListVO.setType("site");
            childCompanyListVO.setCompanyList(childCompanyListVOList);
            return Collections.singletonList(childCompanyListVO);
        }
        List<String> companyIds = new ArrayList<>();
        List<String> groupIds = new ArrayList<>();
        for (ChannelCompanyVO channelCompanyVO : channelCompanyVOList) {
            if (channelCompanyVO.getIsAllEmployer()) {
                groupIds.add(channelCompanyVO.getChildCompanyId());
            } else {
                companyIds.add(channelCompanyVO.getEmployerId());
            }
        }
        List<ChildCompanyListVO> resultList = new ArrayList<>();
        Set<String> haveGroupCompanyIds = new HashSet<>();
        for (ChildCompanyListVO childCompanyListVO : childCompanyListVOList) {
            List<ChildCompanyListVO> companyList = childCompanyListVO.getCompanyList();
            // 只有组权限的 只放入对应组
            if (CollectionUtils.isEmpty(companyList)) {
                continue;
            }
            // 分组中含有部分公司权限
            if (!groupIds.contains(childCompanyListVO.getId())) {
                // 有权限的用工单位
                List<ChildCompanyListVO> hadCompanyList = new ArrayList<>();
                for (ChildCompanyListVO companyListVO : companyList) {
                    // 过滤掉没有权限的公司
                    if (companyIds.contains(companyListVO.getId())) {
                        // 有权限的公司
                        hadCompanyList.add(companyListVO);
                        haveGroupCompanyIds.add(companyListVO.getId());
                    }
                }
                companyList = hadCompanyList;
            }
            if (CollectionUtils.isEmpty(companyList)) {
                continue;
            }
            childCompanyListVO.setCompanyList(companyList);
            resultList.add(childCompanyListVO);
        }
        companyIds.removeAll(haveGroupCompanyIds);
        for (String companyId : companyIds) {
            CompanyVO companyVO = companyService.selectBaseCompanyById(companyId, siteId);
            ChildCompanyListVO childCompanyListVO = companyVO.to(ChildCompanyListVO.class);
            childCompanyListVO.setType("company");
            childCompanyListVO.setUuid(UUID.randomUUID().toString().replace("-", ""));
            resultList.add(childCompanyListVO);
        }
        return resultList;
    }

    @Override
    public List<String> selectCompanyIdsByUserId(String userId, String siteId) {
        return channelCompanyDAO.selectCompanyIdsByUserId(userId, siteId);
    }

    /**
     * 根据查询参数，构建example
     *
     * @param channelCompanyQuery 查询参数
     * @param siteId              所属站点id
     * @return example
     */
    private Example buildExample(ChannelCompanyQuery channelCompanyQuery, String siteId) {
        Example example = new Example(ChannelCompanyDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        // 排序
        ExampleKit.setExampleOrder(example, channelCompanyQuery.getOrders());
        return example;
    }
}




